define(function(require, exports, module) {
    require('basic');
    require('jquerytmpl');
    var config = require('config');
    var user = require('user');
    var data_str = user.info.leadPost;

    var model = function(){
        this.autoAdd = false;
        this.stepCookie = {};
        this.potData = {};
        this.copy_data = {};
        this.init();
        //console.log(config.login)
    };

    model.prototype ={
        init: function(){
            this.addEvents();
            if($('#pool_list').length){//判断加载list
                this.loadList();
            }
            if($('#pool_pot').length){//判断加载pot
                this.loadPot();
            }
        },
        /**
         * [loadList /pool/list 获取pot池列表]
         * @return {[type]} [description]
         */
        loadList: function(){
            var sf = this;
            
            $.ajax({
                type: "GET",
                url: config.pool_list+data_str,
                dataType: 'json',
                success: function(data){
                    for(var i=0;i<data.length;i++){
                        data[i]['all'] = data[i]['up']+data[i]['down'];
                    };
                    $('#pool_list tbody').html('');
                    $("#poolListTemplate").tmpl(data).appendTo("#pool_list tbody");
                    var wrap = $('#pool_list'),
                        pop = $('#deletepool');
                    sf.checkAll(wrap);
                    setTimeout(function(){
                        sf.loadList();
                    },30000);
                    //删除pool
                    $('#delete_popbtn').off('click').on('click',function(){
                        var checked_arr = [],
                            index = 0;
                        wrap.find('tbody input:checkbox').each(function(ind,el){
                            if($(this).prop('checked')){
                                checked_arr.push({poolid:$(this).data('poolid'),name:$(this).data('name')});
                            }
                        });
                        if(checked_arr.length>0){
                            pop.find('tbody').html('');
                            $("#poolDeleteTemplate").tmpl(checked_arr).appendTo(pop.find('tbody'));
                            pop.modal({keyboard: false, show: true});
                            $('#delete_btn').off('click').on('click',function(){
                                for(var o=0;o<checked_arr.length;o++){
                                    $.ajax({
                                        type: "DELETE",
                                        url: config.pool+'/'+checked_arr[o]['poolid']+data_str,
                                        dataType: 'json',
                                        success: function(data){
                                            index++;
                                            if(index>=checked_arr.length){
                                                window.location.reload();
                                            };
                                        } 
                                    });
                                };
                            });
                            $('#cancel_btn').off('click').on('click',function(){
                                pop.modal('hide');
                            });
                        }else{
                            alert('请选择资源池！');
                        };
                    });
                } 
            });
        },
        /**
         * [loadPot /pool/{name} 获取pot池详细信息]
         * @return {[type]} [description]
         */
        loadPot: function(){
            var sf = this;
            
            var pool_id = $.QueryString('pool_id'),
                pool_name = $.QueryString('pool_name');
            this.potData['pool'] = pool_id;
            if(pool_id){
                $('h4.tit_name').text('当前主机池：'+pool_name);
                $.ajax({
                    type: "GET",
                    url: config.pool+'/'+pool_id+'/list'+data_str,
                    dataType: 'json',
                    success: function(data){
                        for(var i=0;i<data.length;i++){
                            data[i]['index'] = i+1;
                            if(data[i]['status']==0){
                                data[i]['status_t'] = '等待注册';
                            }else if(data[i]['status']==01){
                                data[i]['status_t'] = '注册成功';
                            }else if(data[i]['status']==02){
                                data[i]['status_t'] = '注册失败';
                            }else if(data[i]['status']==10){
                                data[i]['status_t'] = '已注销';
                            }else{
                                data[i]['status_t'] = '未知状态';
                            }

                            if(data[i]['running_state']==0){
                                data[i]['running_state_t'] = '未知';
                                data[i]['classID'] = 'question-sign';
                            }else if(data[i]['running_state']==1){
                                data[i]['running_state_t'] = '运行';
                                data[i]['classID'] = 'play';
                            }else if(data[i]['running_state']==2){
                                data[i]['running_state_t'] = '关闭中';
                                data[i]['classID'] = 'eye-close';
                            }else if(data[i]['running_state']==3){
                                data[i]['running_state_t'] = '关闭';
                                data[i]['classID'] = 'remove-sign';
                            }else if(data[i]['running_state']==4){
                                data[i]['running_state_t'] = '异常';
                                data[i]['classID'] = 'exclamation-sign';
                            }else{
                                data[i]['running_state_t'] = '其他';
                                data[i]['classID'] = 'list-alt';
                            }
                        }
                        $('#pool_pot tbody').html('');
                        $("#poolPotTemplate").tmpl(data).appendTo("#pool_pot tbody");
                        sf.checkAll($('#pool_pot'));
                        setTimeout(function(){
                            sf.loadPot();
                        },30000);
                    } 
                });
            }else{
                alert('缺少参数!');
            }
            
        },
        /**
         * [checkAll 全选动作]
         * @param  {[jqobj]} _wrap [description]
         * @return {[type]}       [description]
         */
        checkAll: function(_wrap){
            _wrap.find('input.checked_all').each(function(){
                $(this).removeAttr('checked');
                $(this).change(function(e) {
                    var bl = $(this).prop('checked');
                    _wrap.find('input.form_checkbox').prop({checked:bl});
                });
            });
        },
        /**
         * [getElement 获取当前步骤的blok和wrap,ps是第一步的参数]
         * @param  {[type]} a [当前步骤的string,ps:第一步就是'step_1']
         * @param  {[type]} b [下一步骤的string,ps:第一步的下一步是'step_2']
         * @return {[type]}   [两个步骤的block和wrap]
         */
        getElement: function(a,b){
            var items = {};
            if(a){
                items.now = a;
                items.block = $('#add_host_'+a);
                items.wrap = items.block.find('table.table-list tbody');
            };
            if(b){
                items.prev = b;
                items.prevBlock = $('#add_host_'+b);
                items.prevWrap = items.prevBlock.find('table.table-list tbody');
            };
            return items;
        },
        /**
         * [showStep1 显示第一步的内容，载入第一步的事件]
         * @return {[type]} [nothing]
         */
        showStep1: function(){
            var sf = this;
            
            items = this.getElement('step_1');
            items.block.modal({keyboard: false, show: true});
            $.ajax({
                type: "GET",
                url: config.pot_source_list+'/'+data_str,
                dataType: 'json',
                success: function(data){
                    for(var i=0;i<data.length;i++){
                        data[i]['index'] = i;
                    };
                    sf.sourceListData = $.merge(data, [{id:i+1,name:'manual',comment:'手工输入已就绪主机的的信息并添加到主机池',index:i,checked:'checked'}]);
                    items.wrap.html($("#potSourceTemplate").tmpl(sf.sourceListData)).find('input:radio').each(function(index,el){
                        if(sf.sourceListData[index]['checked']){
                            $(el).prop('checked',true);
                        };
                        if($(this).prop('checked')){
                            sf.stepCookie[items.now] =  sf.sourceListData[index];
                        };
                        $(el).on('change',function(){
                            sf.stepCookie[items.now] =  sf.sourceListData[index];
                        });
                    });
                    items.wrap.find('tr').each(function(){
                        $(this).on('click',function(e){
                           $(this).find('input:radio').prop({checked:true}).change();
                        });
                    });
                } 
            });
        },
        /**
         * [showStep2 显示第二步part1的内容，载入第二步part1的事件]
         * @return {[type]} [nothing]
         */
        showStep2: function(){
            var sf = this,
                items = this.getElement('step_2','step_1');

            items.prevBlock.find('input:radio').each(function(index,el){
                if($(this).prop('checked')){
                    sf.stepCookie[items.prev] =  sf.sourceListData[index];
                };
                $(el).on('change',function(){
                    sf.stepCookie[items.prev] =  sf.sourceListData[index];
                });
            });
            items.wrap.find('tr').each(function(){
                $(this).on('click',function(e){
                   $(this).find('input:radio').prop({checked:true});
                });
            });
            this.stepCookie[items.now] = {};
            this.stepCookie[items.now]['number'] = items.block.find('input.form_number').val();
            if(this.stepCookie[items.prev]){
                this.potData['potsrc'] = this.stepCookie[items.prev]['name'];
                $('.selected_source').text(this.stepCookie[items.prev]['name']);
                items.prevBlock.modal('hide');
                items.block.modal({keyboard: false, show: true});
            }else{
                return false;
            };

        },
        /**
         * [showStep2_1 显示第二步part2的内容，载入第二步part2的事件]
         * @return {[type]} [nothing]
         */
        showStep2_1: function(){
            var sf = this,
                items = this.getElement('step_2_1','step_2');
            this.stepCookie[items.prev]['number'] = items.prevBlock.find('input.form_number').val();
            this.stepCookie[items.prev]['potTy'] = items.prevBlock.find('input[name=potTy]:checked').val();
            this.stepCookie[items.prev]['ty'] = items.prevBlock.find('input[name=potTy]:checked').data('cn');
            this.stepCookie[items.now] = this.stepCookie[items.now] ? this.stepCookie[items.now] : {};
            this.stepCookie[items.now]['arr'] = this.stepCookie[items.now]['arr'] ? this.stepCookie[items.now]['arr'] : [];
            this.stepCookie[items.now]['num'] = this.stepCookie[items.now]['num'] ? this.stepCookie[items.now]['num'] : 0;
            if(this.stepCookie[items.prev]['number']){
                this.potData['ty'] = this.stepCookie[items.prev]['potTy'];
                if(this.stepCookie && this.stepCookie[items.now]['num']){
                    //
                }else{
                    this.stepCookie[items.now]['num'] = this.stepCookie[items.prev]['number'];
                };
                var num = this.stepCookie[items.now]['num'];
                $('.selected_number').text(num);
                $('.selected_ty').text(this.potData['ty']);
                var getValue = function(_tr){
                    var tr_data = [];
                    _tr.find('input').each(function(index,el){
                        tr_data[index] = $(el).val();
                    });
                    return tr_data;
                };
                var setValue = function(_tr,data){
                    if(data){
                        _tr.find('input').each(function(index,el){
                            if(index!=0){
                                $(el).val(data[index]).change();
                            };
                        });
                    }else{
                        _tr.find('input').each(function(index,el){
                            $(el).val('').change();
                        });
                    };
                };
                /**
                 * [creatHtml 创建第二步part2的tablelist]
                 * @param  {[type]} _num [tr的数量]
                 * @return {[type]}      [nothing]
                 */
                function creatHtml(_num){
                    var n = _num-items.wrap.find('tr').length;
                    if(n>0){
                        for(var i=0;i<n;i++){
                            var tr = $("#potLineTemplate").tmpl().appendTo(items.wrap);
                            
                        };
                    }else{
                        items.wrap.find('tr').each(function(index,item){
                            if(index>=_num){
                                $(item).remove();
                            };
                        });
                    };
                    items.wrap.find('tr').each(function(index,item){
                        $(item).find('input').each(function(ind,itm){
                            if(ind==0){
                                $(itm).val('pot-'+$.randomNumber());
                            };
                            var oo = index;
                            sf.stepCookie[items.now]['arr'][oo] = sf.stepCookie[items.now]['arr'][oo] ? sf.stepCookie[items.now]['arr'][oo] : [];
                            sf.stepCookie[items.now]['arr'][oo][ind] = $(itm).val(); 
                            $(itm).off('change').on('change',function(){
                                sf.stepCookie[items.now]['arr'][oo][ind] = $(itm).val();
                                //console.log(sf.stepCookie[items.now]['arr'][oo],oo)
                            });
                        });
                        $(item).find('button').eq(0).off('click').on('click',function(e){
                           sf.copy_data = getValue($(item));
                        });
                        $(item).find('button').eq(1).off('click').on('click',function(e){
                            setValue($(item),sf.copy_data);
                        });
                        $(item).find('button').eq(2).off('click').on('click',function(e){
                            setValue($(item));
                        });
                        $(item).find('button').eq(3).off('click').on('click',function(e){
                            --sf.stepCookie[items.now]['num'];
                            sf.stepCookie[items.now]['arr'] = $.grep( sf.stepCookie[items.now]['arr'], function(n,i){
                                return i!=index;
                            });
                            $('.selected_number').text(sf.stepCookie[items.now]['num']);
                            $(item).remove();
                            creatHtml(sf.stepCookie[items.now]['num']);
                        });
                    });
                    
                };
                creatHtml(num);
                items.block.find('tfoot button').off().on('click',function(){
                    sf.stepCookie[items.now]['num']++;
                    $('.selected_number').text(sf.stepCookie[items.now]['num']);
                    creatHtml(sf.stepCookie[items.now]['num']);
                });
                items.prevBlock.modal('hide');
                items.block.modal({keyboard: false, show: true});
            }else{
                return false;
            };
        },

        /**
         * [showStep3 显示第三步的内容，载入第三步的事件]
         * @return {[type]} [nothing]
         */
        showStep3: function(){
            var sf = this,
                items = this.getElement('step_3','step_2_1'),
                step_bl = true,
                tpArr = [];
            this.potArr = [];
            items.prevWrap.find('tr').each(function(ind,itm){
                var pot = {};
                $(itm).find('input').each(function(index,el){
                    var cc = $[$(el).data('rule')]($(el).val());
                    var postName = $(el).data('pots');
                    pot[postName] = $(el).val();
                    if(!cc){
                        step_bl = false;
                        $(el).addClass('error');
                    }else{
                        $(el).removeClass('error');
                    };
                });
                $.extend(pot, sf.potData);
                sf.potArr.push(pot);
            });
            //console.log(sf.potArr)
            if(step_bl){
                items.prevBlock.modal('hide');
                items.block.modal({keyboard: false, show: true});
                items.wrap.html('');
                $("#potViewTemplate").tmpl(sf.potArr).appendTo(items.wrap);
            }else{
                return false;
            };
            
        },
        /**
         * [addEvents 各步骤上一步下一步的事件,.done是最后提交按钮]
         */
        addEvents: function(){
            var sf = this;
            $('#hostcheck').off('click').on('click',sf.hostCheckStep1); //点击主机检查按钮
            $('#checkstep1 #submit1').off('click').on('click',sf.hostCheckStep2); //主机检查第二步，真正调接口的地方
            $('#addpool form').each(function(index, el) {//添加pool
                $(el).find('button').on('click',function(){
                    var name = $.trim($(el).find('input[name="name"]').val());
                    var strategy = $(el).find('select').val();
                    $.ajax({
                        type: "POST",
                        url: config.pool_create+data_str,
                        data: '{"name": "'+name+'","allocation_strategy": "'+strategy+'"}',
                        dataType: 'json',
                        success: function(data){
                            window.location.reload();
                        },
                        error: function(e){
                            $('#error_body').html('').html(e.responseText);
                            $('#error').modal({keyboard: false, show: true});
                        }
                    });
                });
            });
            $('#open_add_host_block').off('click').on('click',function(){
                sf.showStep1();
            });
            $('#add_host_step_2 button.prev').off('click').on('click',function(){
                sf.showStep1();
            });
            $('#add_host_step_2_1 button.prev').off('click').on('click',function(){
                sf.showStep2();
            });
            $('#add_host_step_3 button.prev').off('click').on('click',function(){
                sf.showStep2_1();
            });
            $('#add_host_step_1 button.next').off('click').on('click',function(){
                sf.showStep2();
                return false;
            });
            $('#add_host_step_2 button.next').off('click').on('click',function(){
                sf.showStep2_1();
            });
            $('#add_host_step_2_1 button.next').off('click').on('click',function(){
                sf.showStep3();
            });
            $('#add_host_step_3 button.done').off('click').on('click',function(){
                var ajaxUrl = '';
                if(sf.autoAdd){ //还未区分自动添加和手动添加
                    ajaxUrl = config.pot_auto_create;
                }else{
                    ajaxUrl = config.pot_hand_create;
                };
                
                var d = sf.potArr;
                var pots_data_arr = [];
                for(var i=0;i<d.length;i++){
                    pots_data_arr.push({"account":d[i]['account'],"hostname":d[i]['hostname'],"ip":d[i]['ip'],"password":d[i]['password']})
                };
                var pots_data = {"pool":d[0]['pool'],"pots":pots_data_arr,"potsrc":d[0]['potsrc'],"ty":d[0]['ty']},
                    post_pots_data = JSON.stringify(pots_data);
                $.ajax({
                    type: "POST",
                    url: ajaxUrl+data_str,
                    data: post_pots_data,
                    dataType: 'json',
                    beforeSend: function () {
                        $('.loading').show();
                    },
                    success: function(data){
                        $('.loading').hide();
                        $('#add_host_step_3').modal('hide');
                        //window.location.reload();
                    },
                    error: function(e){
                        $('#error_body').html('').html(e.responseText);
                        $('#error').modal({keyboard: false, show: true});
                    }
                });
                return false;
            });
        },
        /**
         * [hostCheckStep1 主机检查第一步]
         * @return {[type]} [description]
         */
        hostCheckStep1: function(){
            var pop = $('#checkstep1');
            pop.modal({keyboard: false, show: true,}).off('shown.bs.modal').on('shown.bs.modal',function (e) {
                
            });
        },
        /**
         * [hostCheckStep2 主机检查第二步]
         * @return {[type]} [description]
         */
        hostCheckStep2: function(){
            alert('去接口一个个检查状态！');
        }
    };
    

    module.exports = new model();

    
});

